<?php


namespace app\controller;


use app\interceptor\BaseInterceptor;
use app\model\SysUser;
use app\validate\user\Login;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Cache;
use think\response\Json;

class User extends BaseInterceptor
{
    /**
     * 用户登录
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function login(): Json
    {
        $data = $this->request->post();
        $valid = new Login();

        if ($valid->check($data)) {
            $table = new SysUser();
            $user = $table->where(["account" => $data['account']])->find();
            if (is_null($user)) return \json(["code" => 400, "msg" => "账号不存在！"]);
            if ($user->password !== md5($data['password'])) return \json(["code" => 401, "msg" => "密码不正确！"]);
            if ($user->status == 0) return \json(["code" => 401, "msg" => "该账号已停用，暂时无法登录！"]);
            if ($user->role_id == 0) return \json(["code" => 500, "msg" => "该账号暂未配置角色，请联系管理员处理！"]);

            $user->last_login_time = date("Y-m-d H:i:s");
            $user->save();

            $userInfo = $user->hidden(["password"])->toArray();
            $token = $this->encodeToken(['id'=>$user->id]);
            Cache::set($token, $userInfo);

            return \json(["code" => 200, "data" => $token]);
        } else {
            return \json(["code" => 400, "msg" => $valid->getError()]);
        }
    }

    /**
     * 获取用户信息
     * @return Json
     */
    public function getUserInfo(): Json
    {
        if (!$this->isLogin()) return \json(["code" => 401, "msg" => "登录状态已过期，请重新登录！"]);
        $token = $this->getHeaderToken();
        return json(["code" => 200, "data" => Cache::get($token)]);
    }

    /**
     * 更新用户信息
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function updateUserInfo(): Json
    {
        if (!$this->isLogin()) return \json(["code" => 401, "msg" => "您尚未登录！"]);

        $data = $this->request->post();
        $user_id = $this->decodeToken();
        $user = SysUser::find($user_id);
        if (!empty($data['password'])) $data["password"] = md5($data["password"]);
        $user->allowField(["avatar,nickname,password,sex"])->save($data);
        $token = $this->getHeaderToken();
        Cache::set($token, $user->hidden(["password"])->toArray());
        return \json(["code" => 200, "msg" => "更新成功！"]);
    }
}